package cn.example.web.db.dao;

import org.artifact.core.db.MySqlDao;
import org.artifact.core.lang.StrPlus;
import java.util.List;
import java.util.ArrayList;
import java.text.MessageFormat;
import java.util.function.BiFunction;
import org.artifact.core.db.BaseBean;
import cn.hutool.core.map.MapUtil;
import java.util.Map;
import java.util.HashMap;
import org.artifact.core.db.BaseDao;
import cn.example.web.db.bean.Order;
import static cn.hutool.core.util.ObjectUtil.equal;

public abstract class OrderDAO extends MySqlDao<Order>{
	
	protected final String sqlAllColumn = "id, status, create_date, modified_date";

	protected final String sqlAllPla = "?,?,?,?";

	@Override
	protected String getDBName() {
		return "example_web";
	}
	
	@Override
	protected String getTableName() {
		return "t_order";
	}
	
	@Override
	protected Class<Order> getEntityClass(){
		return Order.class;
	}
	
	@Override
	protected Order createEntity() {
		return new Order() {};
	}

	@Override
	protected String getPKFieldName() {
		return "id";
	}
	
	// 根据主键导出
	public Map<String,Object> exportByPrimaryKey(long id,BiFunction<BaseDao,BaseBean,Object> function){
		return export(findByPrimaryKey(id),function);
	}
	
	
	public Map<String,Object> export(Order order,BiFunction<BaseDao,BaseBean,Object> function){
		Map<String,Object> data = new HashMap<>();
		data.put("self", function.apply(this,order));
		return data;
	}
	
	public List<Map<String,Object>> export(List<Order> orders,BiFunction<BaseDao,BaseBean,Object> function){
		List<Map<String,Object>> data = new ArrayList<>();
		for(Order order : orders){
			data.add(export(order,function));
		}
		return data;
	}


	public Order _import(Map<String,Object> data,BiFunction<BaseDao,Map,BaseBean> function){
	    Order order = createEntity();
	    order = (Order)function.apply(this,MapUtil.get(data,"self",Map.class));

        return order;
    }

    public List<Order> _import(List<Map<String,Object>> data,BiFunction<BaseDao,Map,BaseBean> function){
        List<Order> list = new ArrayList<>();
        for(Map<String,Object> map : data){
            list.add(_import(map,function));
        }
        return list;
    }
	
	
	@Override
	public boolean createTable(){
		StrPlus plus = StrPlus.b("CREATE TABLE IF NOT EXISTS `t_order` (");
		plus.a("  `id` bigint(20) NOT NULL COMMENT '主键',");
		plus.a("  `status` varchar(45) NOT NULL COMMENT '状态:0.创建 1.成功  2.失败',");
		plus.a("  `create_date` datetime NOT NULL COMMENT '创建时间',");
		plus.a("  `modified_date` datetime NOT NULL COMMENT '修改时间',");
		plus.a("  PRIMARY KEY (`id`)");
		plus.a(") ENGINE=InnoDB DEFAULT CHARSET=utf8  COMMENT='订单';");
		update(plus.e());
		return true;
	}
	
	@Override
	protected String getSaveSql() {
		return MessageFormat.format("REPLACE INTO {0} ({1}) VALUES ({2})",getTableName(),sqlAllColumn,sqlAllPla);
	}

	@Override
	protected String getDeleteSql() {
		return MessageFormat.format("DELETE FROM {0} WHERE id = ?",getTableName());
	}
	
}